package com.lipaluma.field.validator.impl.string;

import java.lang.reflect.Field;
import java.util.Arrays;

import com.lipaluma.annotations.validations.Validate;
import com.lipaluma.context.Context;
import com.lipaluma.exceptions.CsvParserException;
import com.lipaluma.field.validator.impl.generic.AbstractIsIncludedInValidator;
import com.lipaluma.xml.validator.XmlIncludedInValidator;
import com.lipaluma.xml.validator.XmlValidator;

/**
 * Validate a String field to check that the value of the field must be included in at least one of different given values.<br/>
 * 
 * <p>
 * For Initialisation :
 * <ul>
 * 	<li>
 * 	<u><b>By annotations :</b></u> Use {@link Validate}, with the attribute <code>includedIn = {"a", "b", "c"}</code> 
 * to specify the list of values accepted. <br/>
 * </li>
 * 	<li>
 * 	<u><b>By Xml :</b></u>
 * <ul>
 * This validator may be added using xml mapping with the element <code>includedIn</code> like below : <br/>
 * <code>
 * &lt;ToMap field="..."   ...><br/>
 * <b>
 * &nbsp;&nbsp;&nbsp;&lt;includedIn><br/>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value>a&lt;/value><br/>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value>b&lt;/value><br/>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;value>c&lt;/value><br/>
 * &nbsp;&nbsp;&nbsp;&lt;/includedIn><br/>
 * </b>
 * &lt;/ToMap>
 * </code>
 * </li>
 * </ul>
 * @author Mario
 *
 */
public class StringIncludedInValidator extends AbstractIsIncludedInValidator<String> {

	public StringIncludedInValidator() {}
	public StringIncludedInValidator(String... values) {
		if(values == null)
			throw new CsvParserException("Error on setting "+this.getClass()+" : given values can't be null");
		init(Arrays.asList(values));		
	}
	public boolean init(Context context, Field field) {
		Validate annotation = field.getAnnotation(Validate.class);
		if(annotation == null || annotation.includedIn().length == 0)
			return false;
		
		init(Arrays.asList(annotation.includedIn()));
		return true;
	}
	
	public boolean init(Context context, Field field, XmlValidator xmlValidator) {
		XmlIncludedInValidator validator = (XmlIncludedInValidator) xmlValidator;		
		init(Arrays.asList(validator.getValues()));
		return true;
	}
	
}
